<?php

namespace app\beautiful\controller\admin;

use app\beautiful\model\CouponModel;
use app\beautiful\model\LevelBenefitsModel;
use app\beautiful\model\LevelModel;

use app\beautiful\model\mall\GoodsCategoryModel;
use app\beautiful\model\member\MemberModel;

use app\BaseController;

use app\beautiful\model\setting\LevelSettingModel;
use app\common\logic\DataLogic;
use app\stores\model\member\MemberLevelModel;
use think\facade\Db;


class Level extends BaseController{

    protected $name='会员等级';



    public function index()

    {
        $type=$this->request->param('type/d',0);

        $where=[

            ['is_delete','=',0],

            ['shop_id','=',$this->request->shopId]

        ];
        if($type<1){

            $level_set = LevelSettingModel::where(['shop_id'=>$this->request->shopId,'is_selected'=>1])->find();

            $type = $level_set->type;
        }

        if($type>0) $where[]=['type','=',$type];

        $levelModel=new LevelModel();

        $order=['vip_level'=>'asc'];

        $field="*";

        $append=['add_time_format'];

        $return=DataLogic::getDataList($levelModel,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        return $this->success($return);

    }



    public function show()

    {

        $level_id=$this->request->param('level_id/d',0);

       if($level_id==0){

            $vip_levels=LevelModel::where([

                    ['shop_id','=',$this->request->shopId],

                    ['is_delete','=',0]

                ])->column('vip_level') ?? [];

            if(count($vip_levels) >=5){

                return $this->error($this->name.'已超过五个，无法添加了');

            }

            return $this->success(['vip_levels'=>$vip_levels]);

        }

        if(null === $level = LevelModel::find($level_id)){

            return $this->error($this->name.'不存在');

        }



        if($level->is_delete !=0){

            return $this->error($this->name.'不存在');

        }



        if($level->shop_id != $this->request->shopId){

            return $this->error($this->name.'不存在');

        }

        $detail=[

            'name'=>$level->name,

            'vip_level'=>$level->vip_level,

            'need_integral'=>$level->need_integral,

            'need_recharge'=>$level->need_recharge,

            'discount'=>$level->discount,

        ];



        $vip_levels=LevelModel::where([

                ['shop_id','=',$this->request->shopId],

                ['is_delete','=',0],

                ['vip_level','<>',$level->vip_level]

            ])->column('vip_level') ?? [];

        return $this->success(['detail'=>$detail,'vip_levels'=>$vip_levels]);

    }

    public function save()

    {

        $level_id=$this->request->param('level_id/d',0);

        $name=$this->request->param('name');

        $vip_level=$this->request->param('vip_level/d');

        $need_integral=$this->request->param('need_integral/d',0);

        $need_recharge=$this->request->param('need_recharge/d',0);

        $discount=$this->request->param('discount/f',0);


        if(empty($name) || mb_strlen($name) >10){

            return $this->error($this->name.'名称必须填写且长度不能多余10');

        }

        if(empty($vip_level) || !in_array($vip_level,[1,2,3,4,5])){

            return $this->error('请选择'.$this->name);

        }

        if(empty($need_integral) || $need_integral<=0){

            return $this->error('请填写需要达到的积分，且积分不能小于0');

        }

        if(empty($need_recharge) || $need_recharge<=0){

            return $this->error('请填写需要达到的充值数，且充值数不能小于0');

        }

        if(empty($discount) || $discount<=0){

            return $this->error('请填写优惠折扣，且折扣不能小于0');

        }



        //与低一级进行判断

        $down_level=LevelModel::where([

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

            ['vip_level','<',$vip_level],

            ['level_id','<>',$level_id]

        ])->order(['vip_level'=>'desc'])->find();

        if(null !== $down_level){

            if($need_integral < $down_level->need_integral){

                return $this->error('达到的积分不能小于低一级的积分数');

            }

            if($need_recharge < $down_level->need_recharge){

                return $this->error('达到的充值数不能小于低一级的充值数');

            }

            if($discount > $down_level->discount){

                return $this->error('优惠折扣不能高于于低一级的优惠折扣');

            }

        }



        //与高一级的进行判断

        $up_level=LevelModel::where([

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

            ['vip_level','>',$vip_level],

            ['level_id','<>',$level_id]

        ])->order(['vip_level'=>'asc'])->find();

        if(null !== $up_level){

            if($need_integral > $up_level->need_integral){

                return $this->error('达到的积分不能高于高一级的积分数');

            }

            if($need_recharge > $up_level->need_recharge){

                return $this->error('达到的充值数不能高于高一级的充值数');

            }
            if($discount < $up_level->discount){

                return $this->error('优惠折扣不能低于于高一级的优惠折扣');

            }

        }



        if($level_id!=0){

            if(null === $level =LevelModel::find($level_id)){

                return $this->error($this->name.'不存在');

            }

            if($level->is_delete !=0){

                return $this->error($this->name.'不存在');

            }

            if($level->shop_id != $this->request->shopId){

                return $this->error($this->name.'不存在');

            }

        }else{

            $level_count=LevelModel::where([

                    ['shop_id','=',$this->request->shopId],

                    ['is_delete','=',0],

                ])->count() ?? 0;

            if($level_count>=5){

                return $this->error('只能添加五个');

            }

            $level = new LevelModel();

            $level->shop_id=$this->request->shopId;

        }



        $level->name=$name;

        $level->vip_level=$vip_level;

        $level->need_integral=$need_integral;

        $level->need_recharge=$need_recharge;

        $level->discount=$discount;

        $level->save();

        return $this->success('编辑成功');

    }

    public function del()

    {

        $level_id=$this->request->param('level_id/d',0);

        $from_type=$this->request->param('from_type/d',1);

        if(null === $level =LevelModel::find($level_id)){

            return $this->error($this->name.'不存在');

        }

        if($level->is_delete !=0){

            return $this->error($this->name.'不存在');

        }

        if($level->shop_id != $this->request->shopId){

            return $this->error($this->name.'不存在');

        }

        if($level->is_base ==1){

            return $this->error('系统自带的三个不可删除');

        }

        if($from_type==2){
           $model = new MemberLevelModel();

        }else{
            $model = new MemberModel();
        }
        if(null !== $model::where([

                ['shop_id','=',$this->request->shopId],

                ['is_delete','=',0],

                ['level_id','=',$level_id]

            ])->find()){

            return $this->error('会员等级底下还有会员，暂不可删除');

        }

        $level->is_delete=1;

        $level->save();

        LevelBenefitsModel::where(['level_id'=>$level_id,'shop_id'=>$this->request->shopId])->save(['is_delete'=>1]);

        return $this->success('删除成功');

    }

    /*多店版*/
    /**
     * 添加产品获取等级
     */
    public function getSelectedLevelList(){
        $select_setting = LevelSettingModel::where(['shop_id'=>$this->request->shopId,'is_selected'=>1])->find();
        if($select_setting->type>0){
            $where=[
                ['type','=',$select_setting->type],
                ['is_delete','=',0],
                ['shop_id','=',$this->request->shopId]
            ];

            $levelModel=new LevelModel();
            $order=['vip_level'=>'asc'];
            $field="*";
            $append=['add_time_format'];
            $return=DataLogic::getDataList($levelModel,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        }else{
            $return['total']=0;
            $return['list']=[];
        }
        return $this->success($return);
    }
    /**
     * 显示等级列表
     */
    public function indexLevel()

    {
        $type = $this->request->param('type/d',0);

        $is_set_member_level = $this->request->param('is_set_member_level/d',0);//会员列表会员设置

        if($is_set_member_level){

            $level_set = LevelSettingModel::where(['shop_id'=>$this->request->shopId,'is_selected'=>1])->find();

            $type = $level_set->type;
        }
        $where = [

            ['is_delete','=',0],

            ['shop_id','=',$this->request->shopId],

            ['type','=',$type]

        ];

        $levelModel = new LevelModel();

        $order = ['vip_level'=>'asc'];

        $field = "name,level_id,vip_level,discount_force,price,need_recharge,need_recharge_type,add_time,time_type,type";

        $append = ['add_time_format'];

        $return = DataLogic::getDataList($levelModel,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        $lists = $return['list'];

        foreach ($lists as $key=>$value){

            $benefits = LevelBenefitsModel::with(['coupon'])
                    ->where(['level_id'=>$value['level_id'],'shop_id'=>$this->request->shopId,'type'=>1,'is_delete'=>0])
                    ->field('level_id,type,coupon_id,type_id,num,is_delete')
                    ->select()->toArray() ?? [];
            $gifts_benefits = [];
            foreach ($benefits as $k=>$v) {
                if($v['coupon_id']){
                    $gifts_benefits[] = [
                        'coupon_name'=>$v['coupon']['name'],
                        'money_limit'=>$v['coupon']['money_limit'],
                        'num'=>$v['num']
                    ];
                }

            }

            $lists[$key]['gifts_benefits'] = $gifts_benefits;
        }
        if($is_set_member_level == 1){
            $lists[] =  [
                'name'=>'普通会员',
                'level_id'=>0
            ];
            $return['total'] = $return['total'] + 1;
        }


        $return['list'] = $lists;
        return $this->success($return);

    }

    /**
     * 显示等级信息
    */
    public function showLevel()

    {

        $level_id = $this->request->param('level_id/d',0);

        if(null === $level = LevelModel::where(['level_id'=>$level_id])->json(['discount_time'],true)->find()){

            return $this->error($this->name.'不存在');
        }

        if($level->is_delete !=0){

            return $this->error($this->name.'不存在');
        }

        if($level->shop_id != $this->request->shopId){

            return $this->error($this->name.'不存在');
        }
        //获取等级对应的权益列表
        $benefits = LevelBenefitsModel::with(['coupon'])
                ->where(['level_id'=>$level_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])
                ->field('level_id,type,coupon_id,type_id,num')
                ->select()->toArray() ?? [];
        $total_num = 0;
        $gift_cate = $gifts_benefits =[];
        foreach ($benefits as $k=>$v){

            if($v['coupon_id']){

                if($v['type'] == 1){
                    if($v['type_id'] == 1){
                        $cate_name = '普通券';
                    }else if($v['type_id'] == 2){
                        $cate_name = '新人券';
                    }else if($v['type_id'] == 3){
                        $cate_name = '会员券';
                    }else{
                        $cate_name = '';
                    }
                    //统计分类
                    $gift_cate[$v['type_id']] = $v['type_id'];
                    $total_num += $v['num'];

                }
                $gifts_benefits[] = [
                    'type'=>$v['type'],
                    'type_id'=>$v['type_id'],
                    'coupon_id'=>$v['coupon_id'],
                    'cate_name'=>$cate_name,
                    'coupon_name'=>$v['coupon']['name'],
                    'coupon_money'=>$v['coupon']['coupon_money'],
                    'num'=>$v['num']
                ];
            }
        }

        $detail = [
            'level_id'=>$level->level_id,
            'name'=>$level->name,
            'vip_level'=>$level->vip_level,
            'need_recharge'=>$level->need_recharge,
            'need_recharge_type'=>$level->need_recharge_type,
            'type'=>$level->type,
            'discount_force'=>$level->discount_force,
            'total_gift_cate'=>[
                'total_gift_cate_num'=>count($gift_cate),
                'total_num'=>$total_num
            ],
            'gifts_benefits'=>$gifts_benefits,
            'price'=>$level->price,
            'time_type'=>$level->time_type
        ];



        $vip_levels = LevelModel::where([

                ['shop_id','=',$this->request->shopId],

                ['type','=',$level->type],

                ['is_delete','=',0],

                ['vip_level','<>',$level->vip_level]

            ])->column('vip_level') ?? [];

        return $this->success(['detail'=>$detail,'vip_levels'=>$vip_levels]);

    }
    /**
     * 添加/修改等级
    */
    public function saveLevel()

    {

        $level_id=$this->request->param('level_id/d',0);

        $type=$this->request->param('type/d',1);

        $name=$this->request->param('name');

        $vip_level=$this->request->param('vip_level/d');

        $need_recharge=$this->request->param('need_recharge/d',0);

        $need_recharge_type=$this->request->param('need_recharge_type/d',1);

        $gift_benefits=$this->request->param('gift_benefits/a',[]);

        $discount_force=$this->request->param('discount_force/f',0);

        $price=$this->request->param('price/f',0);

        $time_type=$this->request->param('time_type/d',1);//充值会员终身


        if(empty($name) || mb_strlen($name) >10){

            return $this->error($this->name.'名称必须填写且长度不能多余10');

        }

        if(empty($vip_level) || !in_array($vip_level,[1,2,3,4,5])){

            return $this->error('请选择'.$this->name);

        }


        if($type==1 && (empty($need_recharge) || $need_recharge<=0)){

            return $this->error('请填写需要达到的充值数，且充值数不能小于0');

        }

        if(empty($discount_force) || $discount_force<=0){

            return $this->error('请填写优惠折扣，且折扣不能小于0');

        }
//        $level_set = LevelSettingModel::where(['shop_id'=>$this->request->shopId,'is_selected'=>1])->find();
//
//        $level_time_types = explode(',',$level_set);

        if(!in_array($time_type,[1,2,3,4])) return $this->error('会员时限未选择');


        if($type==1){

            //与低一级进行判断

            $down_level=LevelModel::where([

                ['shop_id','=',$this->request->shopId],

                ['is_delete','=',0],

                ['vip_level','<',$vip_level],

                ['level_id','<>',$level_id]

            ])->order(['vip_level'=>'desc'])->find();

            if(null !== $down_level){

                if($need_recharge < $down_level->need_recharge){

                    return $this->error('达到的充值数不能小于低一级的充值数');

                }

                if($discount_force > $down_level->discount){

                    return $this->error('优惠折扣不能高于于低一级的优惠折扣');

                }

            }

            //与高一级的进行判断

            $up_level=LevelModel::where([

                ['shop_id','=',$this->request->shopId],

                ['is_delete','=',0],

                ['vip_level','>',$vip_level],

                ['level_id','<>',$level_id]

            ])->order(['vip_level'=>'asc'])->find();

            if(null !== $up_level){

                if($need_recharge > $up_level->need_recharge){

                    return $this->error('达到的充值数不能高于高一级的充值数');

                }
                if($discount_force < $up_level->discount_force){

                    return $this->error('优惠折扣不能低于于高一级的优惠折扣');

                }

            }
        }


        if($level_id!=0){

            if(null === $level =LevelModel::find($level_id)){

                return $this->error($this->name.'不存在');

            }

            if($level->is_delete !=0){

                return $this->error($this->name.'不存在');

            }

            if($level->shop_id != $this->request->shopId){

                return $this->error($this->name.'不存在');

            }

        }else{


            $level = new LevelModel();

            $data['shop_id']=$this->request->shopId;

        }

        Db::startTrans();

        try{
            $data['type']=$type;
            $data['name']=$name;
            $data['vip_level']=$vip_level;
            $data['need_recharge']=$need_recharge;
            $data['need_recharge_type']=$need_recharge_type;
            $data['discount_force']=$discount_force;
            $data['time_type']=$type==1?2:$time_type;
            if($type==2) $data['price']=$price;

            $level_benefits = new LevelBenefitsModel();

            if($level_id>0){
                $level->where(['level_id'=>$level_id])->update($data);
                //删除之前的权益，重新添加
                $level_benefits->where(['level_id'=>$level_id,'shop_id'=>$this->request->shopId])->save(['is_delete'=>1]);
            }else{
                $data['add_time']=request()->time();
                $data['add_ip']=request()->ip();
                $level_id=$level->insertGetId($data);
            }

            //赠送权益
            if($gift_benefits){
                foreach ($gift_benefits as $k=>$v){
                    $insert_gift_benefits[] = [
                        'shop_id'=>$this->request->shopId,
                        'level_id'=>$level_id,
                        'type'=>1,
                        'coupon_id'=>(isset($v['coupon_id']) && $v['coupon_id'])?$v['coupon_id']:0,
                        'type_id'=>(isset($v['type_id']) && $v['type_id'])?$v['type_id']:0,
                        'num'=>(isset($v['num']) && $v['num'])?$v['num']:0,

                    ];
                }

                $level_benefits->saveAll($insert_gift_benefits);
            }

            Db::commit();
        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
        return $this->success('编辑成功');

    }
    /**
     *删除会员等级
     */
    public function delLevel()

    {

        $level_id=$this->request->param('level_id/d',0);

        if(null === $level =LevelModel::find($level_id)){

            return $this->error($this->name.'不存在');

        }

        if($level->is_delete !=0){

            return $this->error($this->name.'不存在');

        }

        if($level->shop_id != $this->request->shopId){

            return $this->error($this->name.'不存在');

        }

        if($level->is_base ==1){

            return $this->error('系统自带的三个不可删除');

        }

        if(null !== MemberModel::where([

                ['shop_id','=',$this->request->shopId],

                ['is_delete','=',0],

                ['level_id','=',$level_id]

            ])->find()){

            return $this->error('会员等级底下还有会员，暂不可删除');

        }



        $level->is_delete=1;

        $level->save();

        LevelBenefitsModel::where(['level_id'=>$level_id,'shop_id'=>$this->request->shopId])->save(['is_delete'=>1]);

        return $this->success('删除成功');

    }

    /**
     * 获取等级设置信息
     */
    public function showSet(){
        //$type = $this->request->param('type/d',0);

        if(null === $level_setting = LevelSettingModel::where(['is_selected'=>1,'shop_id'=>$this->request->shopId])->field('level_setting_id,type,open_type,time_type,is_selected')->find()){

            $level_setting = new LevelSettingModel();

            $level_setting->type = 0;

            $level_setting->shop_id = $this->request->shopId;

            $level_setting->open_type = null;

            //$level_setting->time_type =1;

            $level_setting->is_selected =1;

            $level_setting->save();

        }
        $level_setting->open_type=$level_setting->open_type?explode(',',$level_setting->open_type):$level_setting->open_type;
        //$level_setting->time_type=$level_setting->time_type?array_map('intval',explode(',',$level_setting->time_type)):[];

        return $this->success(['detail'=>$level_setting]);

    }
    /**
     * 修改等级设置信息(老会员保持原来的时限)
     */
    public function saveSet(){
        $type = $this->request->param('type/d',0);
        $open_type = $this->request->param('open_type');
        //$time_type = $this->request->param('time_type',1);//1年会员2终身3月4季度
        //至少有一个等级才能保存设置
        $level_count = LevelModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'type'=>$type])->count();
        if($type>0 && $level_count<1){
            return $this->error('必须至少有一个等级');
        }

        $select_setting = LevelSettingModel::where(['shop_id'=>$this->request->shopId,'is_selected'=>1])->find();
        //如果设置为充值或者付费 则就不能在修改了，不然产品折扣这些会乱
        if($select_setting && $select_setting->type>0){
            return $this->error('不能修改');
        }

        if(null === $level_setting = LevelSettingModel::where(['type'=>$type,'shop_id'=>$this->request->shopId])->find()){
            $level_setting = new LevelSettingModel();
            $level_setting->shop_id = $this->request->shopId;
        }

        //每月只能修改一次
//        if(date('m')==date('m',strtotime($level_setting->update_time))) return $this->error('每月只能修改一次');

        Db::startTrans();

        try{
            $level_setting->type=$type;

            $level_setting->open_type=$open_type?implode(',',$open_type):$open_type;

            //$level_setting->time_type=$time_type;

            $level_setting->is_selected=1;

            $level_setting->save();

            if($select_setting && $select_setting->type!=$type){

                $select_setting->is_selected=0;

                $select_setting->save();
            }
            Db::commit();
        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

        return $this->success('设置成功');

    }


}

